/*
 * Copyright (C) 2016 - 2016 iFlytek Inc.  Chengdu Office
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.astudio.lhasa.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextHelper {

    public static final String EMPTY_STR = "";

    public static boolean isEmpty(String str) {
        return null == str || str.length() == 0;
    }

    public static void copyTextToClipboard(Context ctx, String text) {
        ClipboardManager clipboard = (ClipboardManager)
                ctx.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(ctx.getPackageName(), text);
        clipboard.setPrimaryClip(clip);
    }

    public static String getTextFromClipboard(Context ctx) {
        ClipboardManager clipboard = (ClipboardManager)
                ctx.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData data = clipboard.getPrimaryClip();
        return data == null ? EMPTY_STR : data.getItemAt(0).getText().toString();
    }

    public static String UCS2String(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }

    public static String String2UCS(String str) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            unicode.append("\\u" + Integer.toHexString(c));
        }

        return unicode.toString();
    }

    public static String BitCorrect(String str) {
        char[] rtChar = new char[4];
        for (int i = 0; i < rtChar.length; i++) {
            rtChar[i] = '0';
        }

        for(int i = str.length() - 1; i >= 0; i --) {
            rtChar[4 - str.length() + i] = str.charAt(i);
        }
        return new String(rtChar);
    }

    public static boolean isTibetanCharacter(String text) {
        String unicodeStr = String2UCS(text).replaceAll("\\\\u", "0").toLowerCase();
        return unicodeStr.startsWith("0f");
    }
}
